import { Control } from 'react-keeper'
import * as Actions from '../Actions'
import config from '../../../config/config'

const initState = {
	tabNavList: [
		{ title: '首页', key: '/', closable: false },
	],
	activeKey: '/',
	menuList: [],
	userInfo: {
	},
	config,
};

const common = (state = initState, action) => {
	switch (action.type) {
		case 'ADD_TAB_NAV':
			let title = action.title;
			if (title === '') {
				let tabIsExist = state.tabNavList.findIndex(item => (item.key === action.key));
				if (tabIsExist >= 0) {
					return {
						...state,
						activeKey: action.key,
					};
				}
				let parentPath = action.keyPath.length > 1 ? action.keyPath[1] : action.keyPath[0];
				let parentMenu = state.menuList.find(item => (item.url === parentPath));
				title = action.keyPath.length > 1 ? parentMenu.child.find(item => (item.url === action.keyPath[0])).name : (parentMenu.child ? parentMenu.child.name : parentMenu.name);
			}
			return {
				...state,
				tabNavList: [
					...state.tabNavList,
					{
						title: title,
						key: action.key,
					},
				],
				activeKey: action.key,
			}
		case 'CHANGE_TAB_NAV':
			Control.go('/admin' + action.key);
			return {
				...state,
				activeKey: action.key,
			}
		case Actions.setUserInfo:
			return {
				...state,
				userInfo: action.userInfo,
			}
		case 'REMOVE_TAB_NAV':
			let tabNavlist = state.tabNavList.filter((item) => item.key !== action.key);
			if (state.activeKey === action.key) {
				let index = state.tabNavList.findIndex(item => item.key === action.key)
				index = (index >= tabNavlist.length) ? -- index : index;
				state.activeKey = tabNavlist[ index ].key;
				Control.go('/admin'+state.activeKey);
			}
			return {
				...state,
				tabNavList: tabNavlist,
				activeKey: state.activeKey,
			}
		case Actions.setMenu:
			let menu = action.result.menusTree;
			return {
				...state,
				menuList: menu
			};
		default:
			return state;
	}
}

export default common;